#!/usr/bin/perl
# 2014/02/07 extract values from specific area to draw graph

use strict;
use warnings;
use IO::File;
use Getopt::Std;
use Carp qw(croak);
$| = 0;

if(@ARGV != 4 or $ARGV[0] eq '--help'){
	die "Usage : $0 -b [bed file] -r [locaion ex. I:2000-3000]\n";
}

my %opt;
getopts("b:r:", \%opt);

my $FILE_bed = $opt{b};
my $target_location = $opt{r};
my ($target_chr, $target_regions) = split /:/, $target_location;
my ($target_start, $target_end) = split /-/, $target_regions;


#---------------------------------------
# BED fileを読み込む
#---------------------------------------
my %gene;
my %BED_NAMES;
my $NUMBER_FILES = 0;
foreach my $file(@ARGV){
	my ($name, $dir, $ext) = &fileparse($file, '\..*');

	$NUMBER_FILES++;
	$BED_NAMES{$name} = $NUMBER_FILES;

	my $fh_in = IO::File->new($file) or die "cannot open $file: $!";
	while($_ = $fh_in->getline()){
		s/\r?\n//;
		my ($chr, $start, $end, @others) = split /\t/;
		for(my $i = $start; $i <= $end; $i++){
			push @{$gene{$chr}{$i}}, $name;
		}
	}
	$fh_in->close();
}



#---------------------------------------
# 出力形式
#---------------------------------------
# 1. position
# 2. value (1: -direction の　gene, 2: +direction のgene, 3: geneの名前を示すための左端の位置に相当する値
# 3.

print "position\tcategory\tname\n";
{
	my $fh;
	if($FILE_bed =~ /\.gz/){
		$fh = IO::File->new("gzip -dc $FILE_bed |") or die "cannot open $FILE_bed: $!";
	}else{
		$fh = IO::File->new($FILE_bed) or die "cannot open $FILE_bed: $!";
	}
	$fh->getline();
	my $chr = '';
	while($_ = $fh->getline()){
		s/\r?\n//;
		my ($chr, $start, $end, $name, $NA, $direction, @others) = split /\t/;
		if($chr eq $target_chr){
			if($target_start <= $end and $start <= $target_end){
				my $score;
				if($direction eq '+'){
					$score = 1;
				}elsif($direction eq '-'){
					$score = 2;
				}else{
					die "direction parameter is something wrong\n";
				}

				print "$start\t3\t$name\n";
				for(my $i = $start; $i <= $end; $i++){
					print "$i\t$score\n";
				}
			}
		}
	}
	$fh->close();
}







